package zzk.gwxer.tttttt.hanlan.ding.vm

import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import zzk.gwxer.tttttt.hanlan.ding.ui.entity.Player
import kotlin.math.max

class MainViewModel : ViewModel() {
    // 总人数(0-4)
    private val _totalPlayer = MutableStateFlow<Int>(4)
    val totalPlayer: StateFlow<Int> = _totalPlayer
    fun updateTotalPlayer(total: Int) {
        _totalPlayer.value = total
        _activePlayerIndex.value = max(_activePlayerIndex.value, _totalPlayer.value)
    }

    // 设置框显示
    private val _showSettings = MutableStateFlow<Boolean>(false)
    val showSettings: StateFlow<Boolean> = _showSettings
    fun switchShowSettings() {
        _showSettings.value = !_showSettings.value
    }

    // 每轮思考时长
    private val _time = MutableStateFlow<Int>(20)
    val time: StateFlow<Int> = _time
    fun updateTime(time: Int) {
        _time.value = time
        _remainingTime.value = time
        _isTimerOn.value = false
    }

    // 所有玩家
    private val players = listOf<Player>(
        Player(Alignment.TopStart, Color(0xFFB22222)),
        Player(Alignment.TopEnd, Color(0xFF00B2EE)),
        Player(Alignment.BottomStart, Color(0xFF4CAF50)),
        Player(Alignment.BottomEnd, Color(0xFFCDAD00)),
    )
    private val _activePlayerIndex = MutableStateFlow<Int>(4)
    val activePlayerIndex: StateFlow<Int> = _activePlayerIndex
    fun updateActivePlayer(index: Int) {
        _activePlayerIndex.value = index
    }
    fun getPlayer(): Player {
        return players[_activePlayerIndex.value]
    }
    fun getAvailablePlayers(): List<Player> {
        return players.slice(0..<totalPlayer.value)
    }
    fun nextPlayer() {
        _activePlayerIndex.value = (_activePlayerIndex.value + 1) % (totalPlayer.value + 1)
    }

    // 倒计时状态
    private val _isTimerOn = MutableStateFlow<Boolean>(false)
    val isTimerOn: StateFlow<Boolean> = _isTimerOn
    fun startTimer() {
        _isTimerOn.value = true
    }
    fun stopTimer() {
        _isTimerOn.value = false
    }
    fun updateTimerState(value: Boolean) {
        _isTimerOn.value = value
    }
    private val _remainingTime = MutableStateFlow<Int>(_time.value)
    val remainingTime: StateFlow<Int> = _remainingTime
    fun resetTimer() {
        _remainingTime.value = _time.value
    }
    fun timerContinueOneSecond() {
        _remainingTime.value = _remainingTime.value - 1
    }
}